﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Xww.LCV.Model.Graphics {
    /// <summary>
    /// 表征有向图，T为顶点类型
    /// </summary>
    /// <typeparam name="T">有向图顶点类型</typeparam>
    public class DirectedGraph<T>:Dictionary<T, List<LinkedListNode<T>>> {
        /// <summary>
        /// 由若干条【边】构建有向图
        /// </summary>
        /// <param name="edges">边(双向链表)的集合</param>
        public DirectedGraph(IEnumerable<LinkedList<T>> edges) {
            foreach (var item in edges) {
                var node = item.First;
                while (node != null) {
                    AddOrUpdateVetex(node.Value, node);
                    node = node.Next;
                }
            }
        }

        ///<summary>添加一个顶点及其对应的双向链表结点集合（如已有记录则附加至原有列表）</summary>
        public void AddOrUpdateVetex(T key, params LinkedListNode<T>[] nodes) {
            if (!this.ContainsKey(key)) {
                this.Add(key, new List<LinkedListNode<T>>());
            }
            this[key].AddRange(nodes);
        }

        ///<summary>输出每个顶点，及每个顶点的边数</summary>
        public override string ToString() {
            StringBuilder rst = new StringBuilder();
            foreach (var item in this) {
                rst.AppendFormat("{0} : {1} nodes", item.Key, item.Value.Count);
                rst.AppendLine();
            }
            return rst.ToString();
        }
    }
}
